import { useState, useRef } from 'react'
import { Link } from 'react-router-dom'
import { Upload, FileText, Image, Video, Music, Archive, X, Check, AlertCircle, Plus, FolderOpen } from 'lucide-react'
import './ResourceImport.css'

const ResourceImport = () => {
  const [dragActive, setDragActive] = useState(false)
  const [uploadedFiles, setUploadedFiles] = useState([])
  const [uploadProgress, setUploadProgress] = useState({})
  const [uploadStatus, setUploadStatus] = useState('idle') // idle, uploading, success, error
  const fileInputRef = useRef(null)

  const getFileIcon = (type) => {
    if (type.startsWith('image/')) return Image
    if (type.startsWith('video/')) return Video
    if (type.startsWith('audio/')) return Music
    if (type.includes('pdf') || type.includes('document')) return FileText
    return Archive
  }

  const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  const handleDrag = (e) => {
    e.preventDefault()
    e.stopPropagation()
    if (e.type === 'dragenter' || e.type === 'dragover') {
      setDragActive(true)
    } else if (e.type === 'dragleave') {
      setDragActive(false)
    }
  }

  const handleDrop = (e) => {
    e.preventDefault()
    e.stopPropagation()
    setDragActive(false)
    
    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      handleFiles(Array.from(e.dataTransfer.files))
    }
  }

  const handleFiles = (files) => {
    const newFiles = files.map(file => ({
      id: Date.now() + Math.random(),
      file,
      name: file.name,
      size: file.size,
      type: file.type,
      status: 'pending',
      progress: 0
    }))
    
    setUploadedFiles(prev => [...prev, ...newFiles])
    setUploadStatus('uploading')
    
    // 模拟上传进度
    newFiles.forEach(fileObj => {
      simulateUpload(fileObj.id)
    })
  }

  const simulateUpload = (fileId) => {
    let progress = 0
    const interval = setInterval(() => {
      progress += Math.random() * 20
      if (progress >= 100) {
        progress = 100
        clearInterval(interval)
        setUploadedFiles(prev => 
          prev.map(file => 
            file.id === fileId 
              ? { ...file, status: 'success', progress: 100 }
              : file
          )
        )
        
        // 检查是否所有文件都上传完成
        setTimeout(() => {
          setUploadedFiles(prev => {
            const allComplete = prev.every(file => file.status === 'success')
            if (allComplete) {
              setUploadStatus('success')
            }
            return prev
          })
        }, 500)
      } else {
        setUploadedFiles(prev => 
          prev.map(file => 
            file.id === fileId 
              ? { ...file, progress }
              : file
          )
        )
      }
    }, 200)
  }

  const removeFile = (fileId) => {
    setUploadedFiles(prev => prev.filter(file => file.id !== fileId))
  }

  const handleFileInput = (e) => {
    if (e.target.files && e.target.files[0]) {
      handleFiles(Array.from(e.target.files))
    }
  }

  const resetUpload = () => {
    setUploadedFiles([])
    setUploadStatus('idle')
    setUploadProgress({})
  }

  const getStatusIcon = (status) => {
    switch (status) {
      case 'success':
        return <Check size={16} className="text-green-500" />
      case 'error':
        return <AlertCircle size={16} className="text-red-500" />
      default:
        return <Upload size={16} className="text-blue-500" />
    }
  }

  return (
    <div className="resource-import">
      <div className="import-header">
        <div className="header-content">
          <h1>资源导入</h1>
          <p>上传和管理您的资源文件</p>
        </div>
        <div className="header-actions">
          <Link to="/resource-library" className="back-btn">
            返回资源库
          </Link>
        </div>
      </div>

      <div className="import-content">
        {/* 上传区域 */}
        {uploadedFiles.length === 0 && (
          <div 
            className={`upload-zone ${dragActive ? 'drag-active' : ''}`}
            onDragEnter={handleDrag}
            onDragLeave={handleDrag}
            onDragOver={handleDrag}
            onDrop={handleDrop}
            onClick={() => fileInputRef.current?.click()}
          >
            <div className="upload-content">
              <Upload size={48} />
              <h3>拖拽文件到此处或点击上传</h3>
              <p>支持 PDF、图片、视频、音频等多种格式</p>
              <div className="upload-formats">
                <span className="format-tag">PDF</span>
                <span className="format-tag">PNG</span>
                <span className="format-tag">JPG</span>
                <span className="format-tag">MP4</span>
                <span className="format-tag">MP3</span>
                <span className="format-tag">DOC</span>
              </div>
            </div>
            <input
              ref={fileInputRef}
              type="file"
              multiple
              onChange={handleFileInput}
              style={{ display: 'none' }}
            />
          </div>
        )}

        {/* 文件列表 */}
        {uploadedFiles.length > 0 && (
          <div className="files-section">
            <div className="files-header">
              <h3>上传文件 ({uploadedFiles.length})</h3>
              {uploadStatus === 'success' && (
                <button onClick={resetUpload} className="reset-btn">
                  <Plus size={16} />
                  继续上传
                </button>
              )}
            </div>

            <div className="files-list">
              {uploadedFiles.map(fileObj => {
                const FileIcon = getFileIcon(fileObj.type)
                return (
                  <div key={fileObj.id} className="file-item">
                    <div className="file-info">
                      <div className="file-icon">
                        <FileIcon size={24} />
                      </div>
                      <div className="file-details">
                        <h4 className="file-name">{fileObj.name}</h4>
                        <p className="file-meta">
                          {formatFileSize(fileObj.size)} • {fileObj.type}
                        </p>
                      </div>
                    </div>

                    <div className="file-status">
                      {fileObj.status === 'pending' && (
                        <div className="upload-progress">
                          <div className="progress-bar">
                            <div 
                              className="progress-fill" 
                              style={{ width: `${fileObj.progress}%` }}
                            />
                          </div>
                          <span className="progress-text">{Math.round(fileObj.progress)}%</span>
                        </div>
                      )}
                      
                      {fileObj.status === 'success' && (
                        <div className="status-success">
                          <Check size={16} />
                          <span>上传完成</span>
                        </div>
                      )}
                      
                      {fileObj.status === 'error' && (
                        <div className="status-error">
                          <AlertCircle size={16} />
                          <span>上传失败</span>
                        </div>
                      )}
                    </div>

                    <div className="file-actions">
                      {fileObj.status !== 'pending' && (
                        <button 
                          onClick={() => removeFile(fileObj.id)}
                          className="remove-btn"
                        >
                          <X size={16} />
                        </button>
                      )}
                    </div>
                  </div>
                )
              })}
            </div>

            {/* 上传完成状态 */}
            {uploadStatus === 'success' && (
              <div className="upload-success">
                <div className="success-content">
                  <Check size={32} />
                  <h3>上传完成！</h3>
                  <p>所有文件已成功上传到资源库</p>
                  <div className="success-actions">
                    <Link to="/resource-library" className="view-library-btn">
                      查看资源库
                    </Link>
                    <button onClick={resetUpload} className="upload-more-btn">
                      继续上传
                    </button>
                  </div>
                </div>
              </div>
            )}
          </div>
        )}

        {/* 导入设置 */}
        <div className="import-settings">
          <h3>导入设置</h3>
          <div className="settings-grid">
            <div className="setting-item">
              <label>
                <input type="checkbox" defaultChecked />
                自动生成缩略图
              </label>
              <p>为图片和视频文件自动生成预览缩略图</p>
            </div>
            
            <div className="setting-item">
              <label>
                <input type="checkbox" defaultChecked />
                提取文件信息
              </label>
              <p>自动提取文件的元数据信息</p>
            </div>
            
            <div className="setting-item">
              <label>
                <input type="checkbox" />
                创建备份
              </label>
              <p>为上传的文件创建备份副本</p>
            </div>
            
            <div className="setting-item">
              <label>
                <input type="checkbox" defaultChecked />
                发送通知
              </label>
              <p>上传完成后发送邮件通知</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

export default ResourceImport
